import React from 'react';
import { Modal, Form, Upload, Button, message } from 'antd';
import { LoadingOutlined, UploadOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import { NumGroupInfo } from '../../../../schema/NumGroup';
import { uploadNumGroup } from '../../../../servers/servers';

/**
 * 号码组props
 */
interface IProps {
  callback?: any; //获取暴露方法
}

/**
 * 号码组state
 */
interface IState {
  // 当前操作弹出弹窗的可见性
  visible: boolean;
  // 当前要上传的号码组Id
  callGroupId: number;
  // 当前上传的文件
  uploadFile?: any;
  // 是否上传中
  uploading: boolean;
}

/**
 * 弹窗-号码组号码上传
 */
export class NumGroupImportPop extends React.Component<IProps, IState> {
  // 表单引用
  private formRef: React.RefObject<FormInstance>;

  constructor(props: IProps) {
    super(props);
    this.formRef = React.createRef<FormInstance>();
    this.state = {
      ...props,
      visible: false,
      callGroupId: 0,
      uploadFile: undefined,
      uploading: false,
    };
  }

  /**
   * 展开弹窗并设置类型
   */
  public open(): void {
    this.setState({
      visible: true,
    });
  }

  /**
   * 关闭弹窗
   */
  public close(): void {
    this.formRef.current?.resetFields();
    this.setState({
      visible: false,
    });
  }

  /**
   * 获取表单值
   */
  public setValue(val: NumGroupInfo) {
    this.setState({
      callGroupId: val?.callGroupId,
    });
  }

  /**
   * 上传前校验
   */
  public beforeUpload(file: any): boolean {
    const allowedExtensions = ['.xls', '.xlsx', '.csv', '.et'];
    const fileName = file.name.toLowerCase();
    const isValid = allowedExtensions.some(ext => fileName.endsWith(ext));
    if (!isValid) {
      message.error('仅支持上传 xls、xlsx、csv 或 et 格式的文件');
      return false;
    }

    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('文件大小超过2M!');
      return false;
    }

    this.setState({
      uploadFile: file,
    });
    return true;
  }
  /**
   * 执行上传
   */
  public handleUpload() {
    const { uploading, uploadFile, callGroupId } = this.state;
    if (uploading) return false;
    this.setState({
      uploading: true,
    });
    const formData = new FormData();
    formData.append('file', uploadFile);
    console.log('号码组Id', callGroupId);
    console.log('开始上传号码文件', uploadFile);
    // 接口
    uploadNumGroup(callGroupId, formData)
      .then(res => {
        if (res.code === 0) {
          this.setState({
            uploading: false,
          });
          message.info('正在导入，请稍候');
          this.close();
          this.props.callback();
        } else {
          message.error(`${res.tips}(错误码: ${res.code})`);
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
        this.setState({
          uploading: false,
        });
        this.close();
      });
  }
  render() {
    const { visible } = this.state;
    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };

    return (
      <>
        <Modal
          title="上传号码组"
          width={500}
          visible={visible}
          footer={null}
          onCancel={() => {
            this.close();
          }}
        >
          <div className="upload-tips">
            导入规则说明：
            <div>
              1.请根据模板调整导入文件，支持<span>xls、xlsx、csv或et格式</span>
              ，大小<span>2M以内</span>；
            </div>
            <div>
              2.一次导入客户数据最多为<span>100,000条</span>。
            </div>
            <div>3.被叫号码为必填字段，必须为纯数字，长度7-11位之间；</div>
            <div>4.支持导入【号码属性管理】中的所有属性。</div>
          </div>
          <Form {...layout} layout="horizontal" ref={this.formRef}>
            <Upload
              name="file"
              accept=".xls,.xlsx,.csv,.et"
              showUploadList={false}
              multiple={false}
              beforeUpload={(file: any) => {
                return this.beforeUpload(file);
              }}
              customRequest={() => {
                this.handleUpload();
              }}
              disabled={this.state.uploading}
            >
              <Button icon={this.state.uploading ? <LoadingOutlined /> : <UploadOutlined />}>
                选择文件上传
              </Button>
            </Upload>
          </Form>
        </Modal>
      </>
    );
  }
}
